import {getUserStatus} from "@/api/user.js"
import { Toast } from "vant"
const vaildTime = 6 * 60 * 60 * 1000 //登录时间缓存6小时

let user = null
let u_name = undefined;
let visitor = false;

//刷新状态函数
export const refreshStatus = async function(){
    let username = u_name ||(u_name = sessionStorage.getItem("username")) 
    //游客刷新直接回到登录页
    if(!username && visitor) return false
    if(username)updateUserStatus(username)  
    return true;
}

//更新用户状态
async function updateUserStatus(username){
    let res = await getUserStatus(username);
    //console.log(status);
    if(res.status == 1) {
        localStorage.setItem("status",res.status)
        sessionStorage.removeItem("visitor")
        visitor = false
    }
    else{
        localStorage.setItem("status",res.status)
        loginByVisitor()  
    }
}

//登录保存状态
export const saveLoginStatus = function(username,college,status){
    localStorage.setItem("user",JSON.stringify({username:username,vaildTime:Date.now() + vaildTime,college:college}))
    localStorage.setItem("status",status);
    if(status !=1){
        loginByVisitor()
    }
    sessionStorage.setItem("username",username);
    u_name = username
    sessionStorage.setItem("college",college);
}

//改变学校状态
export const changeCollege = function(college){
    sessionStorage.setItem("college",college);
    let user = JSON.parse(localStorage.getItem("user"))
    if(user) user.college = college;
    localStorage.setItem("user",JSON.stringify(user))
}

//检查状态
export const checkStatus = function(){
    let info = user || (user = JSON.parse(localStorage.getItem("user")));
    let tag =  visitor || (visitor = sessionStorage.getItem("visitor"))
    //查询数据库更新用户状态(若在每次路由转跳执行则太慢了)
    // if(info.username && !first){
    //     updateUserStatus(info.username);    
    // }
    //是否为游客或非(不可操作点赞、评论、添加)
    if(tag){
        return true
    }
    //过期
    if(!info || !info.vaildTime || Date.now() - info.vaildTime > 0){
        return false
    }
    //第一次进入设置session

    if(info.username && !u_name){
        sessionStorage.setItem("username",info.username);
        sessionStorage.setItem("college",info.college);
        u_name = info.username
    }
         
    return true
}

//清除登录状态
export const clearStatus = function(){
    u_name = user = null
    visitor = false
    sessionStorage.removeItem("visitor")
    sessionStorage.removeItem("college")
    sessionStorage.removeItem("username");
    localStorage.clear()   
}

//游客登录
export const loginByVisitor = function(){
    //表示当前状态为游客登录或未审核用户
    sessionStorage.setItem("visitor",true);
    visitor = true
}

//展示信息组件:回调函数、补充消息
export const showStatusTip = (callback,message)=>{
    let status = localStorage.getItem("status");
    let msg = status==0?"待审核用户":status==-1?"封弊用户":"游客用户"
    Toast.fail({
        message:(msg + message),
        duration:1500,
        forbidClick: true,
        onClose:typeof callback === "function"?callback:undefined
    })
}
